﻿using System;
using System.Linq;
using System.Management;

namespace HybridLab.Virtual.HyperV
{
	public enum JobState : ushort
	{
		New = 2,
		Starting = 3,
		Running = 4,
		Suspended = 5,
		ShuttingDown = 6,
		Completed = 7,
		Terminated = 8,
		Killed = 9,
		Exception = 10,
		Service = 11
	}

	public sealed class Job : IDisposable
	{
		private readonly ManagementObject job;

		public Job(ManagementObject job)
		{
			this.job = job;
		}

		internal ManagementObject RawJob
		{
			get { return job; }
		}

		public JobState State
		{
			get
			{
				job.Get();
				return (JobState)job.Properties["JobState"].Value;
			}
		}

		public decimal PercentComplete
		{
			get
			{
				job.Get();
				return decimal.Parse(job.Properties["PercentComplete"].Value.ToString());
			}
		}

		/// <summary>
		/// Sleep the calling Thread as long as the current Job State is listed among the parameter values.
		/// </summary>
		internal void WaitOn(params JobState[] jobStates)
		{
			while (jobStates.Contains(State))
			{
				System.Threading.Thread.Sleep(100);
			}
		}

		#region Finalize & Dispose
		public void Dispose()
		{
			try
			{
				if (job != null)
				{
					this.job.Dispose();
				}
			}
			finally
			{
				GC.SuppressFinalize(this);
			}
		}

		~Job()
		{
			Dispose();
		}
		#endregion
	}
}
